package com.office.automate.servlet.employee;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.office.automate.dto.convertors.EmployeeDetailsConvertor;
import com.office.automate.exception.framework.FrontierVisibleException;
import com.office.automate.model.employee.Employee;
import com.office.automate.service.def.employee.EmployeeService;
import com.office.automate.service.impl.employee.EmployeeServiceImplementer;
import com.office.automate.validation.framework.ValidatorObject;

/**
 * Servlet implementation class EmployeeRegistration
 */
@WebServlet("/EmployeeRegistrationServlet")
public class EmployeeRegistrationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EmployeeRegistrationServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsp/employee/RegisterNewEmployee.jsp");
		try {
			EmployeeService employeeRegistrationService = new EmployeeServiceImplementer();
			Employee newEmployee = new EmployeeDetailsConvertor().convertRegisterEmployeeRequest(request);
			HashMap<String, FrontierVisibleException> fieldValidationErrors = 
										employeeRegistrationService.validateEmployeeDetails(newEmployee);
			if (fieldValidationErrors != null) {
				request.setAttribute("Employee", newEmployee);
				request.setAttribute("FieldValidationErrors", new ValidatorObject(fieldValidationErrors));
				dispatcher.forward(request, response);		
			} else {
				newEmployee = employeeRegistrationService.registerNewEmployee(newEmployee);
				request.setAttribute("New_Employee", newEmployee);
				dispatcher.forward(request, response);				
			}
		} catch (FrontierVisibleException e) {
			request.setAttribute("OperationalError", e);
			dispatcher.forward(request, response);
		}
	}
}